package com.hk.service.business.parser;

import cn.hutool.core.map.MapUtil;
import com.hk.enums.ContentTypeEnum;
import com.hk.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class ParserBusinessFactory implements ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;

    private static Map<String, AbstractParser> SERVICE_MAP = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, AbstractParser> beansOfType = applicationContext.getBeansOfType(AbstractParser.class);
        if (MapUtil.isNotEmpty(beansOfType)) {
            beansOfType.entrySet().forEach(item -> {
                SERVICE_MAP.put(item.getKey(), item.getValue());
            });
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static AbstractParser parserService(String type) {
        ContentTypeEnum contentEnum = ContentTypeEnum.getContentEnum(type);
        if (Objects.isNull(contentEnum)) {
            throw new BizException("未获取到服务~~");
        }
        AbstractParser abstractParser = SERVICE_MAP.get(contentEnum.name());
        return abstractParser;
    }
}
